import info from "../model/info"
import helper from "./helper"
import api from "../api"
import store from '../store'

const getOpenid = function() {
	let _this = this
	let openid = uni.getStorageSync('openid')
	if (!helper.isEmpty(openid)) {
		return new Promise(resolve => {
			resolve(openid)
		})
	}
	return new Promise((resolve, reject) => {
		uni.login({
			success: function(res) {
				//获取用户信息
				var data = {
					'code': res.code
				}
				api.wxApi.getlogin(data).then(res => {
					let data = info.Login.parse(res.data)
					if (res.code == 200) {
						uni.setStorageSync('openid', data.openid)
						resolve(data.openid)
					} else {
						reject()
					}
				})
			},
		})
	})
}

const getVipByOpenid = function() {
	let is_vip = uni.getStorageSync('is_vip')
	getOpenid().then(openid => {
		let zdy = {
			openid: openid
		}
		if (!helper.isEmpty(is_vip) && is_vip) {
			getUserAssets()
			return false
		}
		api.wxApi.getVipByOpenid(zdy).then(res => {
			let data = info.VipByOpenid.parse(res.data)
			if (helper.isEmpty(data)) return false
			if (!helper.isEmpty(data['phone'])) {
				uni.setStorageSync('user_phone', data.phone)
				uni.setStorageSync('is_vip', true)
				uni.setStorageSync('is_receive_point', data.is_receive_point)
				getUserAssets()
				if (data['is_show_post']) {
					let lookToggle = data['is_show_post'] === 'Y' ? true : false
					uni.setStorageSync('lookToggle', lookToggle)
				}
				typeof callback === 'function' && callback()
			} else {
				uni.setStorageSync('is_vip', false)
			}
		})
	})
}

// 获取用户资产值
const getUserAssets = function() {
	api.wxApi.getPoint().then(res => {
		let data = info.Point.parse(res.data)
		store.dispatch('info_seclect', {
			user_assets: data
		})
	})
}
// 获取用户微信信息
const getWxInfo = function() {
	return new Promise((resolve, reject) => {
		let utoken = uni.getStorageSync("utoken");
		let userLogin = function() {
			uni.login({
				success: function(res) {
					//获取用户信息
					var data = {
						'code': res.code
					};
					api.wxApi.getwxLogin(data).then(json => {
						if (json.success == 1) {
							wx.setStorageSync('utoken', json.utoken);
							wx.setStorageSync('PHPSESSID', json.phpsessid);
							wx.setStorageSync('vip_info', json.vip_info || '');
							resolve();
						} else {
							console.log('post wx login wrong' + json.msg);
							reject(json.msg);
						}
					})
				},
				fail: function(res) {
					// _this.alertMsg('微信登陆授权失败,请关闭微信后重试');
					reject('wx.login失败');
				}
			});
		}
		if (!utoken) {
			userLogin();
		} else {
			//检查登陆态
			uni.checkSession({
				success: function(res) {
					//session 未过期，并且在本生命周期一直有效
					var user_wx_data = wx.getStorageSync('userinfo');
					if (user_wx_data) {
						api.wxApi.getTokenStatus({
							'user_wx_info': JSON.stringify(user_wx_data)
						}).then(json => {
							if (json.success == 1) {
								//写会员信息缓存
								uni.setStorageSync('vip_info', json.vip_info || '');
								uni.setStorageSync('user_auth', true);
								resolve();
							} else {
								console.log('server token fail');
								userLogin();
							}
						})
						resolve();
					} else {
						userLogin();
					}
				},
				fail: function() {
					userLogin();
				}
			})
		}
	})
}

const decryptUserInfo = function(info) {
	const vip_info = uni.getStorageSync('vip_info')
	console.log(typeof vip_info == 'object')
	if (typeof vip_info == 'object') {
		return new Promise(resolve => {
			resolve(vip_info)
		})
	}
	return new Promise((resolve, reject) => {
		api.wxApi.decryptUserInfo(info).then(json => {
			if (json.success == 1) {
				//会员的数据
				uni.setStorageSync('vip_info', json.vip_info || '');
				uni.setStorageSync('user_auth', true);
				console.log('授权成功，回调');
				resolve(json.vip_info)
			} else {
				reject()
			}
		})
	})
	
}

const goBack = function() {
	if (wx.canIUse('navigateBack')) {
		console.log('goBack  navigateBack');
		var pages = getCurrentPages(); //  获取页面栈
		console.log('当前所在的页码数', pages.length)
		if (pages.length <= 1) {
			wx.reLaunch({
				url: '/pages/home/index',
			});
		} else {
			console.log('执行返回了', pages)
			wx.navigateBack({
				delta: 1
			})
		}
	} else {
		console.log('goBack  navigateTo');
		wx.reLaunch({
			url: '/pages/home/index',
		});
	}
}

export default {
	getOpenid,
	getVipByOpenid,
	getUserAssets,
	getWxInfo,
	decryptUserInfo
}
